package tv_megazineplus

import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.QueryParam
import javax.ws.rs.DefaultValue
import javax.ws.rs.core.Response
import org.codehaus.groovy.runtime.TimeCategory


@Path('/api/createAlert')
class CreateAlertResource {

    @GET
    //@Produces('text/plain')
    Response getCreateAlertRepresentation(
        @QueryParam('authToken') String tokenp,
        @QueryParam('progId') String progId,
        @QueryParam('tipoAlerta') String tipo,
        @DefaultValue("5") @QueryParam('minutosAntes') String tempo,
        @QueryParam('personalMessage') String pm) {
        // params: token
        // Programmation program // String personalMessage //Date horaDispara //String tipo
        // createAlertJSON?token=asasasas&progId=121&tipo=sms&tempo=5&pm=sdsdsdsndjbdsb
        def t1 = System.currentTimeMillis()
        
        if(tipo != 'sms' && tipo != 'email')
          return Response.status(400).build();

        if(!pm)
            return Response.status(400).build();
        
        def token = Token.findByToken(tokenp)
        def agora = new Date()
        
        if(token && agora.before(token.expira)){
            def dispara
            use(TimeCategory){
                dispara = Programmation.get(progId).prog_start - tempo.toInteger().minutes
            }
            
                new Alert(user: token.user, program: Programmation.get(progId), personalMessage: pm, horaDispara: dispara, tipo: tipo, sent: 0).save(failOnError: true)
            
                def tt = System.currentTimeMillis() - t1        
                new Statistic(servico: Servicos.findByName('createAlert'), totalTime: tt, date: new Date()).save()    
                
               return Response.status(200).build();
        }else{
            return Response.status(400).build();
        }
        
        
       
        
        //Integer sent
    }
    
    
}
